package com.OrderingSystem.advice;

import cn.hutool.core.date.DateUtil;
import com.OrderingSystem.annotation.LoggerManage;
import com.OrderingSystem.pojo.Systemlog;
import com.OrderingSystem.service.ISystemlogService;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * 日志增强类
 */
@Aspect
@Component
@Slf4j
public class LoggerAdvice {

    @Autowired
    ISystemlogService iSystemlogService;

    @Autowired
    HttpServletRequest request;

    /**
     * 环绕通知
     * 这句话表示的意思是:所有方法如果具有@LoggingManager注解的都会被选中
     */
    @Around("@annotation(loggerManage)")
    public Object addBeforeLogger(ProceedingJoinPoint joinPoint, LoggerManage loggerManage) {
        Object result=null;
        //记录日志，获取目标方法的信息
        Systemlog systemlog=new Systemlog();
        try {
            String openid=request.getParameter("openid");
            systemlog.setLogtype(0);//0  普通日志
            systemlog.setNowuser(openid);//当前用户
            systemlog.setCreatetime(LocalDateTime.now()); // 日志时间
            systemlog.setMethodname(joinPoint.getSignature().getName()); //日志的方法名字

            Object[] parames = joinPoint.getArgs();//方法参数信息
            systemlog.setMethodparms(this.parseParames(parames)); // 方法参数信息

            String value = loggerManage.value();
            systemlog.setLogdescription(value);

            String methodReturnType = loggerManage.methodReturnType();
            systemlog.setMethodtype(methodReturnType);
            //调用目标方法
            result=joinPoint.proceed();
            //方法返回值信息
            systemlog.setMethodteturn(new Gson().toJson(result));
            systemlog.setExmessage("暂无异常");
        } catch (Throwable throwable) {
            //异常日志
            systemlog.setLogtype(1);//1 异常日志
            systemlog.setExmessage(throwable.getMessage());
            throw new RuntimeException(throwable.getMessage());
            //异常信息
        } finally {
            iSystemlogService.save(systemlog); //日志记录到数据库
        }
        return result;
    }

    private String parseParames(Object[] parames) {
        if (null == parames || parames.length <= 0) {
            return "";
        }
        StringBuffer param = new StringBuffer("传入参数 # 个:[ ");
        int i = 0;
        for (Object obj : parames) {
            i++;
            if (i == 1) {
                param.append(obj.toString());
                continue;
            }
            param.append(" ,").append(obj.toString());
        }
        return param.append(" ]").toString().replace("#", String.valueOf(i));
    }
}
